package com.hua.yuan.userlogin.business.dao.impl;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.hua.yuan.base.Constents;
import com.hua.yuan.common.https.OkHttpModule;
import com.hua.yuan.provider.user.IUserProvider;
import com.hua.yuan.provider.user.User;
import com.hua.yuan.userlogin.UserLoginModule;
import com.hua.yuan.userlogin.business.api.IUserLogin;
import com.hua.yuan.userlogin.business.api.IUserSign;
import com.hua.yuan.userlogin.business.callback.IUserLoginCallback;
import com.hua.yuan.userlogin.business.dao.IUserLoginDao;
import com.hua.yuan.userlogin.business.parser.UserLoginResult;
import com.hua.yuan.userlogin.business.result.JsonResult;
import com.hua.yuan.userlogin.business.result.UserSigBean;
import java.io.IOException;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @Author: richsjeson.
 * @Description: TODO()
 * @Date:Created in 2018/12/13 上午9:04.
 * @Modified By: 一开始进入应用 执行用户登录 刷新TOKEN
 */
public class UserLoginDaoImpl implements IUserLoginDao {


    public static final String RTC_TYPE = "rtc";

    private Retrofit mRetrofit;

    private IUserProvider mUserProvider;

    private Disposable mDisposable;

    public UserLoginDaoImpl() {

        mRetrofit = OkHttpModule.getInstance().getRetrofit();
        mUserProvider=UserLoginModule.getInstance().getProvider();
    }

    @Override
    public void userLogin(@NonNull final String pModbilePhone, @NonNull final String pPassword, @NonNull final IUserLoginCallback pLoginCallback) {

        if(mDisposable!=null){
            if(!mDisposable.isDisposed()) {
                mDisposable.dispose();
            }
        }

        mDisposable=Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(ObservableEmitter<String> pEmitter) {

                //无论如何都要刷新Token

                boolean isUserLogin = mUserProvider.getIsLogin();
                String userName = "";
                String password = "";
                //如果用户登录过了，那么则不执行用户登录，反之
                if (isUserLogin) {
                    //执行Token
                    userName = mUserProvider.getMobilePhone();
                    password = mUserProvider.getPassword();

                } else {
                    userName = pModbilePhone;
                    password = pPassword;
                }

                if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
                    pLoginCallback.onResult(null);
                    unOberserval();
                    return;
                }
                //执行用户登录
                IUserLogin userLogin = mRetrofit.create(IUserLogin.class);
                mUserProvider.setMobilePhone(userName).setPassword(password);
                try {
                    Call<String> call = userLogin.userLogin(userName,password);
                    Response<String> response = call.execute();
                    String result = response.body();
                    //如果返回值为空
                    if (TextUtils.isEmpty(result)) {
                        pEmitter.onError(new NullPointerException());
                    }
                    //执行解析操作
                    parserLogin(result,pEmitter);
                } catch (Exception e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }

        }).subscribeOn(Schedulers.newThread())
        .map(new Function<String, UserSigBean>() {

            @Override
            public UserSigBean apply(String pToken) {

                IUserSign userSign = mRetrofit.create(IUserSign.class);
                //登录
                Call<String> call = userSign.getUserSig(pToken, RTC_TYPE);
                try {
                    Response<String> response = call.execute();

                    String result=response.body();
                    if (TextUtils.isEmpty(response.body())) {
                        return null;
                    }
                    JsonResult<JSONObject> resultData = JSONObject.parseObject(result, JsonResult.class);
                    if (resultData == null) {
                        return null;
                    }
                    JSONObject data = resultData.getData();
                    if (data == null) {
                        return null;
                    }
                    UserSigBean targetData = JSONObject.parseObject(data.toJSONString(), UserSigBean.class);
                    if (targetData == null) {
                        return null;
                    }
                    return targetData;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
          })
         .observeOn(AndroidSchedulers.mainThread())
         .subscribe(
                 new Consumer<UserSigBean>() {
                     @Override
                     public void accept(UserSigBean userSigBean) {

                         if (userSigBean == null) {
                             return;
                         }
                         unOberserval();
                         pLoginCallback.onResult(userSigBean);

                     }
                 }, new Consumer<Throwable>() {
                     @Override
                     public void accept(final Throwable throwable) {
                         unOberserval();
                         pLoginCallback.onError(throwable);
                     }
                 });

    }

    private void unOberserval(){
        if(!mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    /**
     * 解析登录
     *
     * @param pResult
     * @param pEmitter
     */
    private void parserLogin(@NonNull String pResult,ObservableEmitter<String> pEmitter) {

        UserLoginResult result = JSONObject.parseObject(pResult, UserLoginResult.class);
        if (result == null) {
            pEmitter.onError(new JSONException("fast json 强制转换失败，请核对数据"));
            return;
        }

        if (result.getErrorCode() != 0) {
            pEmitter.onError(new JSONException(result.getErrorMsg()));
            return;
        }

        if (TextUtils.isEmpty(result.getToken())) {
            pEmitter.onError(new JSONException("Token 不存在"));
            return;
        }

        String token=result.getToken();
        User userInfo = result.getUser();
        if (userInfo == null) {
            pEmitter.onError(new JSONException("用户信息 不存在"));
            return;
        }
        mUserProvider.setUserInfo(userInfo).setToken(token);
        pEmitter.onNext(token);
        pEmitter.onComplete();
    }
}
